<template>
  <div class="container">
    <p class="group-title">普通增加</p>
    <div class="btn-group">
      <button class="btn" @click="decrement">-</button>
      <div class="num">{{ num }}</div>
      <button class="bnt" @click="increment">+</button>
    </div>

    <p class="group-title">Getter 数据</p>
    <div class="btn-group">
      <button class="btn" @click="decrement">-</button>
      <div class="num">{{ doublueCount }}</div>
      <button class="bnt" @click="increment">+</button>
    </div>

    <p class="group-title">异步增加</p>
    <div class="btn-group">
      <button class="btn" @click="asyncDecrement">-</button>
      <div class="num">{{ num }}</div>
      <button class="bnt" @click="asyncIncrement">+</button>
    </div>

    <p class="group-title">store.$reset方法</p>
    <div class="btn-group">
      <button class="btn" @click="counterStore.$reset">重置</button>
    </div>

    <p class="group-title">store.$patch方法</p>
    <div class="btn-group">
      <input type="text" v-model="num" class="numInput" />
      <input type="text" v-model="newnum" class="numInput" />
      <button @click="setHandle">设置</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import useCounterStore from "@/store/counter";
import { storeToRefs } from "pinia";
import { ref } from "vue";

const counterStore = useCounterStore();
const { increment, decrement, asyncIncrement, asyncDecrement } = counterStore;
const { num, doublueCount } = storeToRefs(counterStore);

// 监听store中state的变化
/* counterStore.$subscribe((mutations, state) => {
  console.log("🚀 ~ counterStore.$subscribe ~ mutations:", mutations);
  console.log("🚀 ~ counterStore.$subscribe ~ state:", state);
});
 */
// 监听store中action的变化, 在执行之前发生变化
const unsubscribe = counterStore.$onAction(({ name, store, args }) => {
  console.log("🚀 ~ unsubscribe ~ name, store, args:", name, store, args);
});

const newnum = ref("");
const setHandle = () => {
  counterStore.$patch({
    num: ~~newnum.value,
  });
};
</script>

<style scoped>
.container > .btn-group {
  /* outline: 1px solid red; */
  width: 280px;
  margin: 20px auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.num {
  font-size: 32px;
  font-weight: 300;
}
.btn {
  height: 30px;
  outline: none;
  font-size: 16px;
  font-weight: 100;
  cursor: pointer;
  padding: 0 10px;
}

.numInput {
  width: 200px;
  height: 30px;
  margin-right: 10px;
}

.group-title {
  text-align: center;
  margin-bottom: 0;
  font-weight: 200;
  font-size: 20px;
}
</style>
